<?php

namespace app\common\service\logistics;

use app\common\library\ApiException;
use app\common\model\ExpressAssetslog;
use app\common\model\ExpressOrder;
use app\common\model\ExpressPayaccount;
use app\common\model\ExpressUserApply;
use app\common\model\ExpressUser;
use app\common\model\ExpressWithdraw;
use app\common\model\TerminalExpress;
use think\Db;
use think\Exception;
use think\Request;

/**
 * 快递员管理
 */
class Express
{
    /**
     * 申请为快递员
     * @param $auth
     * @param Request $request
     * @return true
     * @throws ApiException
     */
    public function express_user($auth,Request $request): bool
    {
        $request->filter(['strip_tags']);
        $username = $request->param("username");
        $mobile   = $request->param("mobile");
        if(!$username || !$mobile){
            throw new ApiException("请填写完整信息");
        }
        Db::startTrans();
        try {
            $row = ExpressUserApply::where("user_id",$auth->id)->find();
            if($row){
                if($row["status"] == 0){
                    throw new Exception("资料审核中,请勿操作");
                }
                $res = $row->save([
                    "username" => $username,
                    "mobile"   => $mobile,
                    "status"   => "0"
                ]);
            }else{
                $res = ExpressUserApply::create([
                    "user_id"   => $auth->id,
                    "username"  => $username,
                    "mobile"    => $mobile,
                ]);
            }
            if(!$res){
                throw new Exception("申请失败");
            }
            Db::commit();
            return true;
        }catch (Exception $e){
            Db::rollback();
            throw new ApiException($e->getMessage());
        }
    }

    /**
     * 快递员申请信息
     */
    public function express_user_apply($uid)
    {
        return ExpressUserApply::where("user_id",$uid)
            ->field("id,user_id,username,mobile,status,memo")
            ->find();
    }

    /**
     * 快递员信息
     */
    public function express_user_info($uid=null,$express_id=null)
    {
        if(!$uid && !$express_id){
            return [];
        }
        $w = [];
        if($uid){
            $w["user_id"] = $uid;
        }
        if($express_id){
            $w["id"]    = $express_id;
        }
        $express_user =  ExpressUser::where($w)
            ->find();
        $express_user["avatar"] = \app\common\model\User::where("id",$express_user["user_id"])->value("avatar");
        $express_user["location"] = TerminalExpress::where("user_id",$express_user["user_id"])->value("location");
        if($uid){
            $express_user["order_money"] = ExpressOrder::where("express_uid",$express_user["id"])
                ->where("goods_status","in","1,2")
                ->sum("total_price");
            $express_user["with_num"]    = ExpressWithdraw::where("status",1)->where("express_id",$express_user["id"])->sum("num");
        }
        return $express_user;
    }

    /**
     * 上传轨迹
     * @param $uid
     * @param Request $request
     * @return true
     * @throws ApiException
     */
    public function express_track($uid,Request $request)
    {
        $request->filter(['strip_tags']);
        $lat = $request->param("lat");
        $lnt = $request->param("lnt");
        if(!$lat || !$lnt){
            throw new ApiException("参数错误");
        }
        $express_user = ExpressUser::where("user_id",$uid)->find();
        if(!$express_user){
            throw new ApiException("数据不存在");
        }
        //快递员终端信息
        $terminal_express = TerminalExpress::where("user_id",$uid)->find();
        $terminal = new Terminal();
        if(!$terminal_express){
            //添加终端信息
            TerminalExpress::create([
                "user_id"    => $uid,
                "express_id" => $express_user["id"],
            ]);
            $ter = $terminal->upload_terminal([
                "entity_id"        => $uid."_".$express_user["id"],
                "entity_son_id"    => $express_user["id"],
                "title"            => $express_user["username"]
            ]);
            if(!$ter){
                throw new ApiException("上传终端失败");
            }
        }
        //上传轨迹
        $ter2 = $terminal->upload_express_track($express_user,$lat,$lnt);
        if(!$ter2){
            throw new ApiException("上传轨迹失败");
        }
        return true;
    }

    /**
     * 添加收款信息
     * @param $uid
     * @param Request $request
     */
    public function add_account($uid,Request $request)
    {
        //设置过滤方法
        $request->filter(['strip_tags']);
        $post = $request->post();
        $express_id = ExpressUser::where("user_id",$uid)->value("id");
        if(!$express_id){
            throw new ApiException("获取信息失败");
        }
        $post['express_id'] = $express_id;
        $row = (new ExpressPayaccount())->allowField(true)->save($post);
        if($row){
            return true;
        }else{
            throw new ApiException("添加失败");
        }
    }

    public function account_list($uid)
    {
        $express_id = ExpressUser::where("user_id",$uid)->value("id");
        if(!$express_id){
            throw new ApiException("获取信息失败");
        }
        return ExpressPayaccount::where("express_id",$express_id)->select();
    }

    /**
     * 发起提现
     * @param $uid
     * @param Request $request
     * @return string
     */
    public function add_withdraw($uid,Request $request)
    {
        $request->filter(['strip_tags']);
        $express_info = ExpressUser::where("user_id",$uid)->find();
        if(!$express_info){
            throw new ApiException("获取信息失败");
        }
        $money = $request->param("money",0);
        if(!is_numeric($money) || $money <= 0){
            throw new ApiException("请输入有效数字");
        }
        $account_id = $request->param("account_id");
        $account_info = ExpressPayaccount::where("id",$account_id)->where("express_id",$express_info["id"])->find();
        if(!$account_info){
            throw new ApiException("收款信息不存在");
        }
        $cfg = config('site');
        if($money > $cfg["max_num"]){
            throw new ApiException("提现金额不得超过:".$cfg["max_num"]);
        }
        Db::startTrans();
        try {
            $res1 = ExpressUser::setMoney($uid,$express_info["id"],-$money,"发起提现申请");
            if($res1 !== true){
                throw new Exception("余额不足");
            }
            $charge     = bcmul($money,$cfg["charge"],2);
            $real_num   = bcsub($money,$charge,2);
            $res2 = ExpressWithdraw::create([
                "express_id"    => $express_info["id"],
                "num"           => $money,
                "charge"        => $charge,
                "real_num"      => $real_num,
                "with_type"     => $request->param("with_type"),
                "account_id"    => $account_id,
            ]);
            if(!$res2){
                throw new Exception("添加提现信息失败");
            }
            Db::commit();
            return true;
        }catch (Exception $e){
            Db::rollback();
            throw new ApiException($e->getMessage());
        }
    }

    /**
     * 提现列表
     * @param $uid
     * @param Request $request
     */
    public function withdraw_list($uid,Request $request)
    {
        $request->filter(['strip_tags']);
        $express_info = ExpressUser::where("user_id",$uid)->find();
        if(!$express_info){
            throw new ApiException("获取信息失败");
        }
        $w = [];
        $status = $request->param("status",0);
        $w["status"] = $status;
        $list = ExpressWithdraw::where("express_id",$express_info["id"])
            ->where($w)
            ->order("id desc")
            ->paginate($request->param('limit',15));
        foreach($list as $l){
            $l->createtime = date("Y-m-d H:i:s",$l["createtime"]);
        }

        return $list;
    }

    /**
     * 提现详情
     * @param $uid
     * @param Request $request
     */
    public function withdraw_detail($uid,Request $request)
    {
        $request->filter(['strip_tags']);
        $express_info = ExpressUser::where("user_id",$uid)->find();
        if(!$express_info){
            throw new ApiException("获取信息失败");
        }
        $w = [];
        $id = $request->param("wid");
        $w["id"] = $id;
        $info = ExpressWithdraw::where("express_id",$express_info["id"])
            ->where($w)
            ->find();
        $info->createtime = date("Y-m-d H:i:s",$info["createtime"]);
        return $info;
    }

    /**
     * 收益明细
     * @param $uid
     * @param Request $request
     */
    public function assets_log($uid,Request $request)
    {
        $request->filter(['strip_tags']);
        $express_info = ExpressUser::where("user_id",$uid)->find();
        if(!$express_info){
            throw new ApiException("获取信息失败");
        }
        $info = ExpressAssetslog::where("express_id",$express_info["id"])
            ->where("type","order")
            ->order("id desc")
            ->paginate($request->param("limit",15));
        foreach($info as $i){
            $i->createtime = date("Y-m-d H:i:s",$i["createtime"]);
            $order_info = ExpressOrder::alias("o")
                ->join("address a1","a1.id=o.sending_id")
                ->join("address a2","a2.id=o.receiving_id")
                ->where("o.id",$i["order_id"])
                ->field("o.id as oid,picked_time,receiving_id,sending_id,express_price")
                ->field("a1.name as a1name,a1.mobile as a1mobile,a1.area_address as a1areaaddress,a1.name_address as a1name_address,a1.door_number as a1doornumber,a1.location as a1location")
                ->field("a2.name as a2name,a2.mobile as a2mobile,a2.area_address as a2areaaddress,a2.name_address as a2name_address,a2.door_number as a2doornumber,a2.location as a2location")
                ->find();
            $order_info["picked_time"] = date("Y-m-d H:i:s",$order_info["picked_time"]);
            $i->order_info = $order_info;
        }
        return $info;
    }
}